package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String remember = req.getParameter("remember");

        if (remember == null) {
            remember = "false";
        }

        if (username.equals("admin")) {
            if (password.equals("123456")) {
                //说明用户名和密码正确，将此用户绑定到HttpSession范围
                HttpSession session = req.getSession();
                //为了分辨是谁登录进来的
                session.setAttribute("LOGIN_USER_KEY",username);
                //
                if (remember.equals("true")) {
                    GetSetCookie.set(resp,username,password);
                    System.out.println("list:"+GetSetCookie.get(req));
                }
                //跳转到/WEB-IN/employ/employee
                // req.getRequestDispatcher("/WEB-INF/employ/employee.jsp").forward(req,resp);
                req.getRequestDispatcher("/employee").forward(req,resp);
            } else {
                //说明密码不正确
                System.out.println("密码错误！");
                //绑定数据
                req.setAttribute("PASSWORD_ERROR","密码不正确");
                //转发到login.jsp
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            }
        } else {
            //说明用户名错误
            System.out.println("用户名错误！");
            //绑定数据
            req.setAttribute("USERNAME_ERROR","用户名错误");
            //转发到login.jsp
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
}